<script lang="tsx">

import {h, defineComponent, computed} from 'vue';
import {RouteRecordRaw,useRouter} from "vue-router";
import useSystemStroe from '@/stroe/system.ts'
import MyIcon from '@/components/my-icon/index.vue'
// const menuTree = localStorage.getItem('menuTree')?JSON.parse( localStorage.getItem('menuTree') as string):[]
interface Props{
  menuTree:string;
  theme:string;
}
export default defineComponent({
  emit: ['collapse'],
  props:{
    menuTree:{
      type:Array,
      default:()=>{
        return []
      }
    },
    theme:{
      type:String,
      default:'dark'
    }
  },
  components:{
    MyIcon
  },
  //@ts-ignore
  setup(props:Props,{ emit }) {
    const systemStroe = useSystemStroe();
    const routerKey = computed(()=>systemStroe.routerKey)
    const openKeys = computed(()=>systemStroe.openKey)
    const menuTree = computed(()=>props.menuTree).value
    const collapse = computed(()=>systemStroe.collapsed)
    const theme = computed(()=>props.theme)

    const router = useRouter();
    const goto = (el:any)=>{
      systemStroe.setRouterKey([el.path])
      systemStroe.setOpenKey(el.parentKey)
      router.push({path:`/${el.path}`})

    }
    const collapseClick = ()=>{

      emit('collapse')

    }
    const renderSubMenu = () => {
      function travel(_route: RouteRecordRaw[], nodes = []) {
        if (_route) {
          _route.forEach((element) => {
            // This is demo, modify nodes as needed
            //@ts-ignore
            const icon = element?.icon
                //@ts-ignore
                ? () => h(<myIcon/>,{name: element?.icon})
                : null;
            const title = element?.name
                //@ts-ignore
                ? () => h('span', element.name)
                : null;
            const node = element.children && element.children.length > 0 ? (
                <a-sub-menu
                    key={element?.path}
                    v-slots={{
                      icon,
                      title
                    }}

                >
                  {travel(element?.children)}
                </a-sub-menu>
            ) : (<a-menu-item
                key={element?.path}
                onClick={() => goto(element)}
                v-slots={{
                  icon
                }}
            >
              {element.name}
            </a-menu-item>)
            nodes.push(node as never);
          });
        }
        return nodes;
      }
    //@ts-ignore
      return travel(menuTree);
    };
    return () => (
        <div>
          <a-menu mode="inline"
                  theme={theme.value}
                  openKeys={openKeys.value}
                  selectedKeys={routerKey.value}>
            {renderSubMenu()}

          </a-menu>

  </div>
  )
  }
})
</script>

<style scoped lang="scss">


</style>
